<?php

/**
 * 图片的扩展名
 * @param $filename
 * @return string
 */
function image_ext($filename)
{
    return strtolower(substr(strrchr($filename, '.'), 1));
}

/**
 * 生成安全的图片名称
 * @param $filename
 * @param $dir
 * @return string
 */
function image_safe_name($filename, $dir)
{
    $time = time();
    $s1 = substr($filename, 0, strrpos($filename, '.'));
    $s2 = substr(strrchr($filename, '.'), 1);
    $s1 = preg_replace('#\W#', '_', $s1);
    $s2 = preg_replace('#\W#', '_', $s2);
    if (is_file($dir . "$s1.$s2")) {
        $newname = $s1 . $time . rand(1, 1000) . '.' . $s2;
    } else {
        $newname = "$s1.$s2";
    }
    return $newname;
}

/**
 * 随机生成缩略图文件名
 * @param $filename
 * @return string
 */
function image_thumb_name($filename)
{
    return substr($filename, 0, strrpos($filename, '.')) . '_thumb' . strrchr($filename, '.');
}

/*
 * 随机生成文件名
 */
function image_rand_name($k)
{
    $time = time();
    return $time . '_' . rand(1000000000, 9999999999) . '_' . $k;
}

/**
 * 根据图片文件名生成图片存储路径
 * @param $id
 * @param $dir
 * @return string
 */
function image_set_dir($id, $dir)
{
    $id = sprintf("%09d", $id);
    $s1 = substr($id, 0, 3);
    $s2 = substr($id, 3, 3);
    $dir = $dir . "$s1/$s2";
    !is_dir($dir) && mkdir($dir, 0777, TRUE);
    return "$s1/$s2";
}

/**
 * 根据文件名获取图片存储路径
 * @param $id
 * @return string
 */
function image_get_dir($id)
{
    $id = sprintf("%09d", $id);
    $s1 = substr($id, 0, 3);
    $s2 = substr($id, 3, 3);
    return "$s1/$s2";
}

/**
 * 缩略图
 * @param $sourcefile
 * @param $destfile
 * @param $forcedwidth
 * @param $forcedheight
 * @return array|int[]
 */
function image_thumb($sourcefile, $destfile, $forcedwidth = 80, $forcedheight = 80)
{
    $return = array('filesize' => 0, 'width' => 0, 'height' => 0);
    $destext = image_ext($destfile);
    if (!in_array($destext, array('gif', 'jpg', 'bmp', 'png'))) {
        return $return;
    }
    $imginfo = getimagesize($sourcefile);
    $src_width = $imginfo[0];
    $src_height = $imginfo[1];
    if ($src_width == 0 || $src_height == 0) {
        return $return;
    }
    if (!function_exists('imagecreatefromjpeg')) {
        copy($sourcefile, $destfile);
        $return = array('filesize' => filesize($destfile), 'width' => $src_width, 'height' => $src_height);
        return $return;
    }
    $src_scale = $src_width / $src_height;
    $des_scale = $forcedwidth / $forcedheight;
    if ($src_width <= $forcedwidth && $src_height <= $forcedheight) {
        $des_width = $src_width;
        $des_height = $src_height;
    } elseif ($src_scale >= $des_scale) {
        $des_width = ($src_width >= $forcedwidth) ? $forcedwidth : $src_width;
        $des_height = $des_width / $src_scale;
        $des_height = ($des_height >= $forcedheight) ? $forcedheight : $des_height;
    } else {
        $des_height = ($src_height >= $forcedheight) ? $forcedheight : $src_height;
        $des_width = $des_height * $src_scale;
        $des_width = ($des_width >= $forcedwidth) ? $forcedwidth : $des_width;
    }
    switch ($imginfo['mime']) {
        case 'image/jpeg':
            $img_src = imagecreatefromjpeg($sourcefile);
            !$img_src && $img_src = imagecreatefromgif($sourcefile);
            break;
        case 'image/gif':
            $img_src = imagecreatefromgif($sourcefile);
            !$img_src && $img_src = imagecreatefromjpeg($sourcefile);
            break;
        case 'image/png':
            $img_src = imagecreatefrompng($sourcefile);
            break;
        case 'image/wbmp':
            $img_src = imagecreatefromwbmp($sourcefile);
            break;
        default :
            return $return;
    }
    if (!$img_src) return $return;
    $img_dst = imagecreatetruecolor($des_width, $des_height);
    imagefill($img_dst, 0, 0, 0xFFFFFF);
    imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $des_width, $des_height, $src_width, $src_height);
    $tmppath = CacheDir . "tmp/";
    !is_dir($tmppath) && file_mkdirs($tmppath, 0777);
    $tmpfile = $tmppath . md5($destfile) . '.tmp';
    switch ($destext) {
        case 'jpg':
            imagejpeg($img_dst, $tmpfile, 90);
            break;
        case 'gif':
            imagegif($img_dst, $tmpfile);
            break;
        case 'png':
            imagepng($img_dst, $tmpfile);
            break;
    }
    $r = array('filesize' => filesize($tmpfile), 'width' => $des_width, 'height' => $des_height);
    copy($tmpfile, $destfile);
    is_file($tmpfile) && unlink($tmpfile);
    imagedestroy($img_dst);
    return $r;
}

/**
 * 图片裁剪
 * @param $sourcefile
 * @param $destfile
 * @param $clipx
 * @param $clipy
 * @param $clipwidth
 * @param $clipheight
 * @return false|int
 */
function image_clip($sourcefile, $destfile, $clipx, $clipy, $clipwidth, $clipheight)
{
    $getimgsize = getimagesize($sourcefile);
    if (empty($getimgsize)) {
        return 0;
    } else {
        $imgwidth = $getimgsize[0];
        $imgheight = $getimgsize[1];
        if ($imgwidth == 0 || $imgheight == 0) {
            return 0;
        }
    }
    if (!function_exists('imagecreatefromjpeg')) {
        copy($sourcefile, $destfile);
        return filesize($destfile);
    }
    switch ($getimgsize[2]) {
        case 1 :
            $imgcolor = imagecreatefromgif($sourcefile);
            break;
        case 2 :
            $imgcolor = imagecreatefromjpeg($sourcefile);
            break;
        case 3 :
            $imgcolor = imagecreatefrompng($sourcefile);
            break;
    }
    if (!$imgcolor) return 0;
    $img_dst = imagecreatetruecolor($clipwidth, $clipheight);
    imagefill($img_dst, 0, 0, 0xFFFFFF);
    imagecopyresampled($img_dst, $imgcolor, 0, 0, $clipx, $clipy, $imgwidth, $imgheight, $imgwidth, $imgheight);
    $tmppath = CacheDir . "tmp/";
    $tmpfile = $tmppath . md5($destfile) . '.tmp';
    imagejpeg($img_dst, $tmpfile, 100);
    $n = filesize($tmpfile);
    copy($tmpfile, $destfile);
    is_file($tmpfile) && @unlink($tmpfile);
    return $n;
}

/**
 * 裁剪后生成缩略图
 * @param $sourcefile
 * @param $destfile
 * @param $forcedwidth
 * @param $forcedheight
 * @return false|int|mixed
 */
function image_clip_thumb($sourcefile, $destfile, $forcedwidth = 80, $forcedheight = 80)
{
    $getimgsize = getimagesize($sourcefile);
    if (empty($getimgsize)) {
        return 0;
    } else {
        $src_width = $getimgsize[0];
        $src_height = $getimgsize[1];
        if ($src_width == 0 || $src_height == 0) {
            return 0;
        }
    }
    $src_scale = $src_width / $src_height;
    $des_scale = $forcedwidth / $forcedheight;
    if ($src_width <= $forcedwidth && $src_height <= $forcedheight) {
        $des_width = $src_width;
        $des_height = $src_height;
        $n = image_clip($sourcefile, $destfile, 0, 0, $des_width, $des_height);
        return filesize($destfile);
    } elseif ($src_scale >= $des_scale) {
        $des_height = $src_height;
        $des_width = $src_height / $des_scale;
        $n = image_clip($sourcefile, $destfile, 0, 0, $des_width, $des_height);
        if ($n <= 0) return 0;
        $r = image_thumb($destfile, $destfile, $forcedwidth, $forcedheight);
        return $r['filesize'];
    } else {
        $des_width = $src_width;
        $des_height = $src_width / $des_scale;
        $n = image_clip($sourcefile, $destfile, 0, 0, $des_width, $des_height);
        if ($n <= 0) return 0;
        $r = image_thumb($destfile, $destfile, $forcedwidth, $forcedheight);
        return $r['filesize'];
    }
}

/**
 * 图片生成缩略图
 * @param $sourcefile
 * @param $id
 * @param $ext
 * @param $dir1
 * @param $forcedwidth
 * @param $forcedheight
 * @param $randomname
 * @return array|int[]
 */
function image_safe_thumb($sourcefile, $id, $ext, $dir1, $forcedwidth, $forcedheight, $randomname = 0)
{
    $time = time();
    $ip = ip();
    $dir2 = image_set_dir($id, $dir1);
    $filename = $randomname ? md5(rand(0, 1000000000) . $time . $ip) . $ext : $id . $ext;
    $filepath = "$dir1$dir2/$filename";
    $arr = image_thumb($sourcefile, $filepath, $forcedwidth, $forcedheight);
    $arr['fileurl'] = "$dir2/$filename";
    return $arr;
}

/**
 * 将base64保存为图片
 * @param $imgBase64
 * @param $filename
 * @return false|string
 */
function saveBase64Image($imgBase64, $filename = "")
{
    $base64_image_content = $imgBase64;
    //匹配出图片的格式
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
        $type = strtolower($result[2]);
        $exts = "jpg,jpeg,png,gif,bmp";
        if (stripos($exts, $type) === false) {
            return false;
        }
        if (!$filename) {
            $new_file = PublicRoot . UploadDir . "/image/" . date("Ymd") . "/";
            if (!file_exists($new_file)) {
                mkdir($new_file, 0777);
            }
            $new_file = $new_file . getCuid() . ".{$type}";
        } else {
            $new_file = $filename;
        }
        if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content))) !== false) {
            return SystemDir . $new_file;
        } else {
            return false;
        }
    }
    return false;
}


/**
 * 制作缩略图,支持png和jpg，还能保留png透明度
 * @param $from
 * @param $to
 * @param $towidth
 * @param $toheight
 * @param $scaleType int 缩放模式，0智能，1按照宽度等比，2按照高度等比，3拉伸
 * @return bool
 * @throws ImagickException
 */
function sltMaker($from, $to, $towidth, $toheight, $scaleType = 0)
{
    $im = new Imagick();
    /* Read the image file */
    $im->readImage($from);

    // 按指定大小生成缩略图，而且不变形，缩略图函数
    list($fw, $fh, $type) = getimagesize($from);

    if ($scaleType == 0) {
        // 使缩略后的图片不变形，并且限制在 缩略图宽高范围内
        if ($fw / $towidth > $fh / $toheight) {
            $toheight = $towidth * ($fh / $fw);
        } else {
            $towidth = $toheight * ($fw / $fh);
        }
    } else if ($scaleType == 1) {
        $toheight = $towidth * ($fh / $fw);
    } else if ($scaleType == 2) {
        $towidth = $toheight * ($fw / $fh);
    } else if ($scaleType == 3) {
        //不处理，写了要多少就多少，进行拉伸
    }
    $im->thumbnailImage($towidth, $toheight);
    $ret = $im->writeImage($to);
    $im->destroy();
    return $ret ? true : false;
}

/**
 * 调用图像处理类
 * @param bool $use_imagick
 * @return \Intervention\Image\ImageManager
 */
function img_manager($use_imagick = false)
{
    $dg_o_imagick = "gd";
    if ($use_imagick) {
        $dg_o_imagick = "imagick";
    }
    return new \Intervention\Image\ImageManager(array('driver' => $dg_o_imagick));
}

/**
 * 图像缩放
 * @param $srcimage
 * @param $dstimage
 * @param $dst_width
 * @param $dst_height
 * @param $backgroundcolor
 * @return bool|string
 */
function imagezoom($srcimage, $dstimage, $dst_width, $dst_height, $backgroundcolor)
{
    $dstimg = imagecreatetruecolor($dst_width, $dst_height);
    $color = imagecolorallocate($dstimg, hexdec(substr($backgroundcolor, 1, 2)), hexdec(substr($backgroundcolor, 3, 2)), hexdec(substr($backgroundcolor, 5, 2)));
    imagefill($dstimg, 0, 0, $color);
    if (!$arr = getimagesize($srcimage)) {
        return false;
    }
    $src_width = $arr[0];
    $src_height = $arr[1];
    $srcimg = null;
    $fd = fopen($srcimage, "rb");
    $data = fread($fd, 3);
    $data = img_str2hex($data);
    if ($data == '474946') {
        $srcimg = imagecreatefromgif($srcimage);
    } elseif ($data == 'FFD8FF') {
        $srcimg = imagecreatefromjpeg($srcimage);
    } elseif ($data == '89504E') {
        $srcimg = imagecreatefrompng($srcimage);
    } else {
        return 'ext error';
    }

    $dst_x = 0;
    $dst_y = 0;
    $dst_w = $dst_width;
    $dst_h = $dst_height;
    if (($dst_width / $dst_height - $src_width / $src_height) > 0) {
        $dst_w = $src_width * ($dst_height / $src_height);
        $dst_x = ($dst_width - $dst_w) / 2;
    } elseif (($dst_width / $dst_height - $src_width / $src_height) < 0) {
        $dst_h = $src_height * ($dst_width / $src_width);
        $dst_y = ($dst_height - $dst_h) / 2;
    }
    imagecopyresampled($dstimg, $srcimg, $dst_x, $dst_y, 0, 0, $dst_w, $dst_h, $src_width, $src_height);
    if ($data == '474946') {
        $a = imagegif($dstimg, $dstimage);
    } elseif ($data == 'FFD8FF') {
        $a = imagejpeg($dstimg, $dstimage);
    } elseif ($data == '89504E') {
        $a = imagepng($dstimg, $dstimage);
    }
    imagedestroy($dstimg);
    imagedestroy($srcimg);
    return $a;
}

/**
 * 字符串转16进制
 * @param $str
 * @return string
 */
function img_str2hex($str)
{
    $ret = "";
    for ($i = 0; $i < strlen($str); $i++) {
        $ret .= ord($str[$i]) >= 16 ? strval(dechex(ord($str[$i]))) : '0' . strval(dechex(ord($str[$i])));
    }
    return strtoupper($ret);
}

/**
 * 获取图形验证码，要求GD库和JPEG扩展
 * @param $sessionKey string 存储的session键
 * @param bool $returnB64 是否返回base64，否则直接页面输出
 * @param int $font_size 字体大小
 * @param int $charLen 输出几个字
 * @param int $img_height 图形高度
 * @param int $img_width 图形宽度
 * @param int $word_type 1、纯数字  2、字母  3、混合
 * @return string 返回base64或直接页面输出
 */
function getValidateImg($sessionKey, $returnB64 = false, $font_size = 14, $charLen = 4, $img_height = 24, $img_width = 68, $word_type = 1)
{
    $config = array(
        'sessionKey' => $sessionKey,
        'font_size' => $font_size,
        'img_height' => $img_height,
        'word_type' => $word_type,    // 1:数字  2:英文   3:混合
        'img_width' => $img_width,
        'use_boder' => TRUE,
        'font_file' => CoreDir . 'vdk/data/fonts/' . mt_rand(1, 3) . '.ttf',
        'filter_type' => 4);
    @session_start();

    //主要参数
    $font_size = isset($config['font_size']) ? $config['font_size'] : 14;
    $img_height = isset($config['img_height']) ? $config['img_height'] : 24;
    $img_width = isset($config['img_width']) ? $config['img_width'] : 68;
    $font_file = isset($config['font_file']) ? $config['font_file'] : CoreDir . 'vdk/data/fonts/' . mt_rand(1, 3) . '.ttf';
    $use_boder = isset($config['use_boder']) ? $config['use_boder'] : TRUE;
    $filter_type = isset($config['filter_type']) ? $config['filter_type'] : 0;

    //创建图片，并设置背景色
    $im = @imagecreate($img_width, $img_height);
    imagecolorallocate($im, 255, 255, 255);

    //文字随机颜色
    $fontColor[] = imagecolorallocate($im, 0x15, 0x15, 0x15);
    $fontColor[] = imagecolorallocate($im, 0x95, 0x1e, 0x04);
    $fontColor[] = imagecolorallocate($im, 0x93, 0x14, 0xa9);
    $fontColor[] = imagecolorallocate($im, 0x12, 0x81, 0x0a);
    $fontColor[] = imagecolorallocate($im, 0x06, 0x3a, 0xd5);

    //获取随机字符
    $rndstring = '';
    if ($config['word_type'] != 3) {
        for ($i = 0; $i < $charLen; $i++) {
            if ($config['word_type'] == 1) {
                $c = chr(mt_rand(48, 57));
            } else if ($config['word_type'] == 2) {
                $c = chr(mt_rand(65, 90));
                if ($c == 'I') $c = 'P';
                if ($c == 'O') $c = 'N';
            }
            $rndstring .= $c;
        }
    } else {
        $chars = 'abcdefghigklmnopqrstuvwxwyABCDEFGHIGKLMNOPQRSTUVWXWY0123456789';
        $rndstring = '';
        $max = strlen($chars) - 1;
        for ($i = 0; $i < $charLen; $i++) {
            $rndstring .= $chars[mt_rand(0, $max)];
        }
    }

    $_SESSION[$config['sessionKey']] = strtolower($rndstring);

    $rndcodelen = strlen($rndstring);

    //背景横线
    $lineColor1 = imagecolorallocate($im, 0xda, 0xd9, 0xd1);
    for ($j = 3; $j <= $img_height - 3; $j = $j + 3) {
        imageline($im, 2, $j, $img_width - 2, $j, $lineColor1);
    }

    //背景竖线
    $lineColor2 = imagecolorallocate($im, 0xda, 0xd9, 0xd1);
    for ($j = 2; $j < 100; $j = $j + 6) {
        imageline($im, $j, 0, $j + 8, $img_height, $lineColor2);
    }

    //画边框
    if ($use_boder && $filter_type == 0) {
        $bordercolor = imagecolorallocate($im, 0x9d, 0x9e, 0x96);
        imagerectangle($im, 0, 0, $img_width - 1, $img_height - 1, $bordercolor);
    }


//    file_put_contents("a.txt", $rndstring . '///' . $rndcodelen);
    //输出文字
    for ($i = 0; $i < $rndcodelen; $i++) {
        $rndstring[$i] = strtoupper($rndstring[$i]);
        $c_fontColor = $fontColor[mt_rand(0, 4)];
        $y_pos = $i == 0 ? 4 : $i * ($font_size + 2);
        $c = mt_rand(0, 15);
        imagettftext($im, $font_size, $c, $y_pos, 19, $c_fontColor, $font_file, $rndstring[$i]);
    }

    //图象效果
    switch ($filter_type) {
        case 1:
            imagefilter($im, IMG_FILTER_NEGATE);
            break;
        case 2:
            imagefilter($im, IMG_FILTER_EMBOSS);
            break;
        case 3:
            imagefilter($im, IMG_FILTER_EDGEDETECT);
            break;
        default:
            break;
    }

    ob_start();
    ob_clean();
    imagejpeg($im);
    $ret = @ob_get_clean();
    $b64_header = "data:image/jpeg;base64,";

    imagedestroy($im);
    if ($returnB64) {
        return $b64_header . base64_encode($ret);
    } else {
        @header("content-type:image/jpeg");
        echo $ret;
    }
    exit();
}

/**
 * 验证图形验证码
 * @param $sessionKey
 * @param $userCode
 * @return bool
 */
function checkValidateCode($sessionKey, $userCode)
{
    @session_start();
//    echo $_SESSION[$sessionKey];
    if (isset($_SESSION[$sessionKey]) && $_SESSION[$sessionKey] === strtolower($userCode)) {
        return true;
    }
    return false;
}

